package com.topfun.utils;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息工具类
 * 
 * @author Administrator
 * 
 */
public class WechatMessageUtil {

	private static final Logger logger                 = LoggerFactory.getLogger(WechatMessageUtil.class);
	/**
	 * 请求消息类型：推送
	 */
	public static final  String REQ_MESSAGE_TYPE_EVENT = "event";



	/**
	 * 事件类型：subscribe(订阅)
	 */
	public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";

	/**
	 * 事件类型：unsubscribe(取消订阅)
	 */
	public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";

	public static final String EVENT_TYPE_CLICK = "CLICK";
	

	/**
	 * 解析微信发来的请求（XML）
	 * 
	 * @param pBody
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> parseXml(String pBody)
			throws Exception {
		// 将解析结果存储在HashMap中
		Map<String, String> map = new HashMap<String, String>();
		// 从request中取得输入流
		InputStream inputStream = new ByteArrayInputStream(pBody.getBytes("UTF-8"));
		// 读取输入流
		SAXReader reader   = new SAXReader();
		Document  document = reader.read(inputStream);
		// 得到xml根元素
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<Element> elementList = root.elements();

		// 遍历所有子节点
		StringBuilder sb = new StringBuilder("收到信息:");
		for (Element e : elementList){
			map.put(e.getName(), e.getText());
			sb.append(String.format(" name:%s value:%s",e.getName(),e.getText()));
		}
		logger.debug(sb.toString());
		// 释放资源
		inputStream.close();

		return map;
	}


}